package com.example.xuanyang.myapplication;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    private String logTag = "myLogTag";
    private String adLogTag = "mytag_fb";
    float mX = 0f;
    float mY = 0f;
    float mPressure = 0f;
    float mSize = 0f;
    float mXPrecision = 0f;
    float mYPrecision = 0f;
    int mMetastate = 0;
    int mEdgeflags = 0;
    int mDeviceId = 0;


    private com.facebook.ads.internal.view.c d;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        Log.i(logTag, "start");

        try{
            Log.i(adLogTag, "begin");
            Log.i(adLogTag, this.getClass().getName());
            Log.i(adLogTag, this.getComponentName().toString());
//            Activity tmp = getActivity();
//            if(tmp != null) {
//                Log.i(adLogTag, tmp.getClass().getName());
//                Log.i(adLogTag, tmp.getComponentName().toString());
//            }else {
//                Log.i(adLogTag, "null");
//            }

            startActivity(new Intent(this, AdActivity.class));
            ActivityManager activityManager = (ActivityManager)(getSystemService(android.content.Context.ACTIVITY_SERVICE));
            List<ActivityManager.RunningTaskInfo> runningTaskInfos = activityManager.getRunningTasks(1) ;
            if(runningTaskInfos != null) {
                ComponentName f = runningTaskInfos.get(0).topActivity;
                String topActivityClassName = f.getClassName();
                Log.i(adLogTag, topActivityClassName);
            }


        }catch (Exception e){
            e.printStackTrace();
        }

        final WebView webView = (WebView) findViewById(R.id.webView);
        webView.loadUrl("http://baidu.com");

        TextView tv = (TextView) findViewById(R.id.myhello);
        tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i(logTag, "textview onClick");
                setSimulateClick(webView);
            }
        });



        // 测试应用重启 表示不好使

//        try{
//            ActivityManager manager = (ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE);
//            manager.restartPackage(getPackageName());
//        }catch (Exception e){
//            e.printStackTrace();
//        }

        webView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // TODO Auto-generated method stub
                //返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器
                view.loadUrl(url);
                return true;
            }
        });

        webView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i(logTag, "webview onClick");
            }
        });

        webView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
//                Log.i(logTag, "onTouch");

                int deviceId = event.getDeviceId();
                float pressure = event.getPressure();
                float size = event.getSize();
                float xPrecision = event.getXPrecision();
                float yPrecision = event.getYPrecision();
                int metastate = event.getMetaState();
                int edgeflags = event.getEdgeFlags();
                float x = event.getX();
                float y = event.getY();
                if(mX == 0f){
                    mX = x;
                    mY = y;
                    mPressure = pressure;
                    mSize = size;
                    mXPrecision = xPrecision;
                    mYPrecision = yPrecision;
                    mMetastate = metastate;
                    mEdgeflags = edgeflags;
                }

                Log.i(logTag, "x:"+x);
                Log.i(logTag, "y:"+y);


                return false;
            }
        });



        //        showLockScreen.setOnTouchListener(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View view, MotionEvent motionEvent) {
//                long time = motionEvent.getDownTime();
//                long etime = motionEvent.getEventTime();
//                int type = motionEvent.getAction();
//                float x = motionEvent.getX();
//                float y = motionEvent.getY();
//
//                int deviceId = motionEvent.getDeviceId();
//                float pressure = motionEvent.getPressure();
//                float size = motionEvent.getSize();
//                float xPrecision = motionEvent.getXPrecision();
//                float yPrecision = motionEvent.getYPrecision();
//                int metastate = motionEvent.getMetaState();
//                int edgeflags = motionEvent.getEdgeFlags();
//
//                AdManager.getInstance(mContext).motionEvent(motionEvent);
//
//                Log.d("event", time + " " + etime + " " + type + " " + x + " " + y + " " + deviceId + " "  + pressure + " " + size + " " + xPrecision + " " + yPrecision + " " + metastate + " " + edgeflags);
//                return false;
//            }
//        });

        Log.i(logTag, "end");

    }







//    private void setSimulateClick(View view) {
//        int width = view.getWidth();
//        int height = view.getHeight();
//        float x = Util.gaussianRandom(0, width);
//        float y = Util.gaussianRandom(0, height);
//        float xadd = Util.gaussianRandom(0, 999999) * 1.0f/ 100000f;
//        float yadd = Util.gaussianRandom(0, 999999) * 1.0f/ 100000f;
//        x += xadd;
//        y += yadd;
//
//        String str = PreferenceUtil.getInstance(mContext).getInputDevice();
//        InputDevice device = InputDevice.fromJsonString(str);
//        if (device == null){
//            return;
//        }
//        float pressure = Double.valueOf(device.getPressure()).floatValue();
//        float orgSize = Double.valueOf(device.getSize()).floatValue();
//        float xPrecision = Double.valueOf(device.getXprecision()).floatValue();
//        float yPrecision = Double.valueOf(device.getYprecision()).floatValue();
//        int metastate = device.getMetaState();
//        int deviceId = device.getDeviceId();
//        int edgeflags = device.getEdgeFlags();
//
//        float addSize = Util.gaussianRandom(0, 1764707)* 1.0f / 1000000000 - 0.000864707f;
//        float size = orgSize + addSize;
//        long downTime = SystemClock.uptimeMillis();
//        long eventTime = downTime;
//        int num = Util.random(0, 4);
//        MotionEvent downEvent = MotionEvent.obtain(downTime, eventTime,
//                MotionEvent.ACTION_DOWN, x, y, pressure, size, metastate, xPrecision, yPrecision, deviceId, edgeflags);
//        view.dispatchTouchEvent(downEvent);
//        float moveSize = size;
//        for(int i = 0; i < num; i++) {
//            eventTime += Util.gaussianRandom(15, 43);
//            if (i == num - 1){
//                moveSize = size;
//            }else{
//                addSize = Util.gaussianRandom(0, 1764707)* 1.0f / 1000000000;
//                moveSize += addSize;
//            }
//            MotionEvent moveEvent = MotionEvent.obtain(downTime, eventTime,
//                    MotionEvent.ACTION_MOVE, x, y, pressure, moveSize, metastate, xPrecision, yPrecision, deviceId, edgeflags);
//            view.dispatchTouchEvent(moveEvent);
//            moveEvent.recycle();
//        }
//        eventTime += Util.gaussianRandom(15, 43);
//        MotionEvent upEvent = MotionEvent.obtain(downTime, eventTime,
//                MotionEvent.ACTION_UP, x, y, pressure, size, metastate, xPrecision, yPrecision, deviceId, edgeflags);
//        view.dispatchTouchEvent(upEvent);
//        downEvent.recycle();
//        upEvent.recycle();
//    }



    private void setSimulateClick(View view) {
        int width = view.getWidth();
        int height = view.getHeight();
        float x = mX;
        float y = mY;
        float pressure = mPressure;
        float orgSize = mSize; // 调试一下边界值
        float xPrecision = mXPrecision;
        float yPrecision = mYPrecision;
        int metastate = mMetastate;
        int deviceId = mDeviceId;
        int edgeflags = mEdgeflags;

        float addSize = Util.gaussianRandom(0, 1764707)* 1.0f / 1000000000 - 0.000864707f;
        float size = orgSize;
        long downTime = SystemClock.uptimeMillis();

        long eventTime = downTime;
        int num = Util.random(0, 4);
        MotionEvent downEvent = MotionEvent.obtain(downTime, eventTime,
                MotionEvent.ACTION_DOWN, x, y, pressure, size, metastate, xPrecision, yPrecision, deviceId, edgeflags);
        view.dispatchTouchEvent(downEvent);
        float moveSize = size;
        for(int i = 0; i < num; i++) {
            eventTime += Util.gaussianRandom(15, 43);
            if (i == num - 1){
                moveSize = size;
            }else{
                addSize = Util.gaussianRandom(0, 1764707)* 1.0f / 1000000000;
                moveSize += addSize;
            }
            MotionEvent moveEvent = MotionEvent.obtain(downTime, eventTime,
                    MotionEvent.ACTION_MOVE, x, y, pressure, moveSize, metastate, xPrecision, yPrecision, deviceId, edgeflags);
            view.dispatchTouchEvent(moveEvent);
            moveEvent.recycle();
        }
        eventTime += Util.gaussianRandom(15, 43);
        MotionEvent upEvent = MotionEvent.obtain(downTime, eventTime,
                MotionEvent.ACTION_UP, x, y, pressure, size, metastate, xPrecision, yPrecision, deviceId, edgeflags);
        view.dispatchTouchEvent(upEvent);
        downEvent.recycle();
        upEvent.recycle();

    }





    public static Activity getActivity() {
        Class activityThreadClass = null;
        try {
            activityThreadClass = Class.forName("android.app.ActivityThread");
            Object activityThread = activityThreadClass.getMethod("currentActivityThread").invoke(null);
            Field activitiesField = activityThreadClass.getDeclaredField("mActivities");
            activitiesField.setAccessible(true);
            Map activities = (Map) activitiesField.get(activityThread);
            for (Object activityRecord : activities.values()) {
                Class activityRecordClass = activityRecord.getClass();
                Field pausedField = activityRecordClass.getDeclaredField("paused");
                pausedField.setAccessible(true);
                if (!pausedField.getBoolean(activityRecord)) {
                    Field activityField = activityRecordClass.getDeclaredField("activity");
                    activityField.setAccessible(true);
                    Activity activity = (Activity) activityField.get(activityRecord);

                    return activity;
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        return null;
    }



}
